/*
 * EasyCamera
 *
 * Copyright (c) 2020.  Frezrik frezrik@126.com
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.camera.widget;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import java.nio.ByteBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class YuvRenderer implements GLSurfaceView.Renderer {

    private YuvProgram mYuvProgram;

    public YuvRenderer(){
        mYuvProgram = new YuvProgram();
    }
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        if (!mYuvProgram.isProgramBuilt())
            mYuvProgram.buildProgram();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        //用黑色清屏
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        mYuvProgram.drawFrame();
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
    }

    public void setResolution(int width, int height) {
        if (mYuvProgram != null)
            mYuvProgram.setResolution(width, height);
    }

    public void setDisplayOrientation(int degrees, boolean needMirror) {
        if (mYuvProgram != null)
            mYuvProgram.setDisplayOrientation(degrees, needMirror);
    }

    public void setYUVRenderData(byte[] y, byte[] u, byte[] v)
    {
        if (mYuvProgram != null)
            mYuvProgram.setYUVRenderData(y, u, v);
    }


    public void release() {
        if (mYuvProgram != null)
            mYuvProgram.releaseProgram();
    }

    public void clear(YuvSurfaceView surfaceView) {
        if (mYuvProgram != null && surfaceView != null)
            mYuvProgram.clear(surfaceView);
    }
}
